package com.motu.monstercity.server.game.logichandler;

import com.motu.monstercity.module.common.iap.Iap;
import com.motu.monstercity.module.common.iap.IapGift;
import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.CsGameIap.*;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.iap.PrivilegeCard;
import com.motu.monstercity.server.game.commondata.iap.Vip;
import com.motu.monstercity.server.game.commondata.iap.GrowthFund;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.base.ServerConfig;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author hxl
 * create date: 2021/12/21
 * 充值协议
 */
public class IapHandler {
    private static Logger logger = LoggerFactory.getLogger(IapHandler.class);

    // CMD_GAME_IAP_INFO = 72200; // 进入充值页面初始化
    public static Object CMD_GAME_IAP_INFO(RequestParam clientParam) throws Exception {
        CSGameIapInfoResponse.Builder response = CSGameIapInfoResponse.newBuilder();
        CSGameIapInfoRequest request = CSGameIapInfoRequest.parseFrom(clientParam.getData());
        long userId = clientParam.getUserId();
        int platform = request.getPlatform();
        long channel = request.getChannel();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        List<UserIapGift> iapGiftTypeList = IapManager.getUserIapGiftList(userId);
//        System.out.println(iapGiftTypeList.size());
        for (UserIapGift userIapGift : iapGiftTypeList) {
            if (userIapGift != null) {
                ProtoDataUtils.updatePBUserData(pbUserData, userIapGift,true);
            }
        }
        return response;
    }

    // CMD_GAME_IAP_BUY = 72202; // iap购买
    public static Object CMD_GAME_IAP_BUY(RequestParam clientParam) throws Exception {
        CSGameIapBuyRequest request = CSGameIapBuyRequest.parseFrom(clientParam.getData());
        CSGameIapBuyResponse.Builder response = CSGameIapBuyResponse.newBuilder();
        long userId = clientParam.getUserId();
        int iapGiftId = request.getIapGiftId();
        IapGift iapGift = IapManager.getIapGift(iapGiftId);
        // 参数错误
        if (iapGift == null) {
            return ErrorWord.BAD_PARAM;
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        JsonObject paramObject = iapGift.getParams();

        int paramModule = request.getParamModule();

        // 各种礼包的限购判断
        Object errorWord = GameIapManager.checkBuyIapGift(userInfo, iapGift);
        if (errorWord != ErrorWord.SUCCESS) {
            return errorWord;
        }

        // 判断免费礼包
        if (iapGift.getIapId() == 0) {
            return GameIapManager.buyFreeIapGift(paramModule,response, paramObject, iapGift, userInfo);
        }

        // 参数错误
        Iap iap = IapManager.getIap(iapGift.getIapId());
        if (iap == null) {
            return ErrorWord.BAD_PARAM;
        }

        String packageName = request.getPackageName();
        String iapProductId = IapManager.getIapProductId(packageName, iap.getId());
        if (iapProductId == null) {
            return ErrorWord.INVALID_OPERATION;
        }

        // 使用顺序：付费代金券>免费代金券>付费代币>免费代币>魔兔币
        int itemType = request.getType();//0充值 1付费代金券 2免费代金券 3付费代币 4免费代币 5魔兔币
        int itemIdFree = ItemId.TYPE_IAP_FREE_PRICE;// 免费代币 isFake=1, 当成虚拟充值，不做充值事件的上报（免费获得的）优先扣除这个

        // 付费代币 TYPE_IAP_PAY_PRICE = 100450; // 付费代币 isFake=0,当成真实充值，会做充值事件的上报
        if (itemType == GameIapManager.IAP_BUY_TYPE_PAY_PRICE){
            if (BagManager.getUserItemNum(userInfo, ItemId.TYPE_IAP_PAY_PRICE) < iap.getPayPrice()) {
                return ErrorWord.ITEM_LACK;
            }
        }
        // 免费代币  TYPE_IAP_FREE_PRICE = 100350 或是  TYPE_IAP_FREE_PRICE_2 = 100351
        else if (itemType == GameIapManager.IAP_BUY_TYPE_FREE_PRICE) {
            if (BagManager.getUserItemNum(userInfo, ItemId.TYPE_IAP_FREE_PRICE) < iap.getPayPrice()) {
                itemIdFree = ItemId.TYPE_IAP_FREE_PRICE_2;// 免费代币 isFake=1, 当成虚拟充值，不做充值事件的上报（充值获得的，如第三方的网页充值）
                if (BagManager.getUserItemNum(userInfo, ItemId.TYPE_IAP_FREE_PRICE_2) < iap.getPayPrice()) {
                    return ErrorWord.ITEM_LACK;
                }
            }
        }
        // 使用魔兔币要判断开关是否开启
        else if (itemType == GameIapManager.IAP_BUY_TYPE_MOTU_MONEY){
            if (!FunctionManager.isFunctionClientOpen(FunctionManager.FUNCTION_ID_MOTU_MONEY, userInfo.getServerId())){
                return ErrorWord.BAD_PARAM;
            }
        }

        //创建iap_click记录
        String uuid = Tool.getUUID();
        String sql = "insert into iap_click(user_id,iap_gift_id,order_id,add_time) values(?,?,?,?);";
        JsonArray params = new JsonArray().add(userId).add(iapGiftId).add(uuid).add(TimeUtils.getCurTime());
        Long newId = Future.await(MysqlTool.insertAndGetID(MysqlClient.getGamePool(), sql, params));
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        if (newId != null) {
            response.setIapGiftId(iapGiftId);
            response.setOrderId(uuid);
            response.setDbId(newId);
            response.setProductId(iapProductId);
            response.setIapId(iap.getId());
            response.setType(itemType);

            UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);

            // 付费代币
            if (itemType == GameIapManager.IAP_BUY_TYPE_PAY_PRICE) {
                RewardManager.subReward(userInfo, ItemId.TYPE_IAP_PAY_PRICE, iap.getPayPrice(), pbUserData, LogType.CHARGE);
            }
            // 免费代币
            else if (itemType == GameIapManager.IAP_BUY_TYPE_FREE_PRICE) {
                RewardManager.subReward(userInfo, itemIdFree, iap.getPayPrice(), pbUserData, LogType.CHARGE);
            }
            // 扣除魔兔币（扣除的同时也会判断魔兔币是否足够，这样不用交互2次）
            else if (itemType == GameIapManager.IAP_BUY_TYPE_MOTU_MONEY){
                try {
                    int motuMoney = Future.await(GameIapManager.subMotuMoney(userExtInfo.getAccountId(), iap.getMotuMoney(), userId, uuid, iapGiftId));
                    response.setMotuMoney(motuMoney);
                } catch (Exception e){
                    String errorCode = e.getCause().getMessage();
                    if (Tool.isNum(errorCode)){
                        return ErrorWord.getEnum(Integer.parseInt(errorCode));
                    } else{
                        return ErrorWord.NET_ERROR_TIMEOUT;
                    }
                }
            }

            // 测试服直接入库,有代金券或代币也直接入库
            if (itemType > 0 || ((ServerConfig.isDebugServer() || ServerConfig.isReviewServer()) && AllParam.TEST_PAY_FINISH == 1)) {
                // 订单入库
                String[] transInfos = {"test", "payItem", "freeItem", "payPrice", "freePrice", "motumoney"};
                String transInfo = transInfos[itemType];
                int isFake;// 是否虚拟补单
                if (itemType == GameIapManager.IAP_BUY_TYPE_PAY_PRICE) {// 付费代币 isFake=0,当成真实充值，会做充值事件的上报
                    isFake = 0;
                } else{
                    isFake = 1;// M币，虚拟代币都当成虚拟补单
                }

                String sql1 = "insert into iap_order(user_id,platform,iap_gift_id,money,diamond,product_id,order_id,trans_info,error_code,is_fake,add_time) values(?,?,?,?,?,?,?,?,?,?,?);";
                JsonArray params1 = new JsonArray();
                params1.add(userId);
                params1.add(userExtInfo.getPlatform());
                params1.add(iapGiftId);
                params1.add(iap.getBiMoney());
                params1.add(iapGift.getDiamond());
                params1.add(iapProductId);
                params1.add(uuid);
                params1.add(transInfo);
                params1.add(1);//订单标记为已处理
                params1.add(isFake);//虚拟补单
                params1.add(TimeUtils.getCurTime());
                Future.await(MysqlTool.updateToDb(MysqlClient.getGamePool(), sql1, params1));
                //查询订单
                String sql2 = "select * from iap_order where order_id = ?;";
                JsonArray params2 = new JsonArray().add(uuid);
                JsonArray array = Future.await(MysqlTool.queryJsonArrayFromDb(MysqlClient.getGamePool(), sql2, params2));
                if (array.size() > 0) {
                    JsonObject iapObj = array.getJsonObject(0);
                    iapObj.put("itemType", itemType);// 付费道具类型
                    Common.PBIapResult.Builder result = GameIapManager.dealOrder(response.getUserBuilder(),userId, iapObj, false);
                    response.setIapResult(result);

                    // 更新iapclick表
                    String sql3 = "update iap_click set callback=?,callback_time=?,status=? where id=?";
                    JsonArray params3 = new JsonArray();
                    params3.add(transInfo);
                    params3.add(TimeUtils.getCurTime());
                    params3.add(1);// 标记未正常到账
                    params3.add(newId);
                    Future.await(MysqlTool.updateToDb(MysqlClient.getGamePool(), sql3, params3));
                }
            }

            return response;
        } else {
            return ErrorWord.MYSQL_INSERT_FAILED;
        }
    }

    //	CMD_GAME_IAP_CANCEL = 72203;// 取消订单
    public static Object CMD_GAME_IAP_CANCEL(RequestParam clientParam) throws Exception {
        CSGameIapCancelResponse.Builder res_build = CSGameIapCancelResponse.newBuilder();
        CSGameIapCancelRequest clientReq = CSGameIapCancelRequest.parseFrom(clientParam.getData());
        String orderId = clientReq.getOrderId();
        int status = clientReq.getStatus();// 取消支付99 支付失败100
        if (status == 0) {
            status = 99;
        }

        if (orderId == null || orderId.length() == 0) {
            return ErrorWord.BAD_PARAM;
        }
        String sql = "update iap_click set status = ? WHERE order_id = ? ;";
        JsonArray params = new JsonArray();
        params.add(status);
        params.add(orderId);
        MysqlTool.updateToDb(MysqlClient.getGamePool(), sql, params, handler -> {
            if (handler.failed()) {
                logger.error(handler.cause().getMessage());
            }
        });
        return res_build;
    }

    // CMD_GAME_IAP_GIFT_PUSH_INFO = 72204; // 推送礼包界面
    public static Object CMD_GAME_IAP_GIFT_PUSH_INFO(RequestParam clientParam) throws Exception {
        long userId = clientParam.getUserId();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        // 功能未开启
//        if (!userInfo.checkModuleOpen(SystemOpen.MODULE_ID_IAP_GIFT_PUSH, 0)) {
//            return ErrorWord.MODULE_LOCKED;
//        }
        long curTime = TimeUtils.getCurTime();
        List<UserIapGiftPush> userIapGiftPushList = GameUser.getUserIapGiftPushList(userId);
        CSGameIapGiftPushInfoResponse.Builder builder = CSGameIapGiftPushInfoResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = builder.getUserBuilder();
        for (UserIapGiftPush userIapGiftPush : userIapGiftPushList) {
            IapGift iapGift = IapManager.getIapGift(userIapGiftPush.getIapGiftId());
            if (iapGift == null) {
                continue;
            }
            if (userIapGiftPush.getEndTime() < curTime) {
                continue;
            }
            ProtoDataUtils.updatePBUserData(pbUserData, userIapGiftPush, true);
        }
        return builder;
    }

//    //CMD_GAME_IAP_GET_MOTU_MONEY = 72205; // 获取魔兔币
//    public static Object CMD_GAME_IAP_GET_MOTU_MONEY(RequestParam clientParam) throws Exception{
//
//        UserInfo userInfo = GameUser.getUserInfo(userId);
//        if (!Function.isOpen(Function.FUNCTION_ID_MOTU_MONEY, userInfo.getServerId())){
//            return ErrorWord.INVALID_OPERATION;
//        }
//
//        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
//        int motuMoney;
//        if (userExtInfo.getAccountType() == LoginManager.LOGIN_TYPE_MOTU_SDK){
//            // 魔兔sdk才需要获取魔兔币
//            try{
//                motuMoney = Sync.awaitResult(h ->GameIapManager.getMotuMoney(userExtInfo.getAccountId(), h));
//            }catch (Exception e){
//                return ErrorWord.NET_ERROR_TIMEOUT;
//            }
//        } else{
//            motuMoney = 0;
//        }
//
//        // 返回客户端数据
//        CSGameIapGetMotuMoneyResponse.Builder response = CSGameIapGetMotuMoneyResponse.newBuilder();
//        response.setMotuMoney(motuMoney);
//        return BaseHandler.getResponseOk(cmdCode,response.build().toByteArray());
//    }

//
//    /**
//     * 获取efun加密透传参数
//     */
//    private static void getEfunParams(long userId, int platform, int iapGiftId, String orderId, String packageName, String productId, int retry, Handler<AsyncResult<JsonObject>> onComplete) {
//        JsonObject objKey = new JsonObject(ServerParam.LOGIN_KEY_EFUN);
//        String loginKey = objKey.getString(packageName);
//
//        // 计算透传参数(userid_platform_iapid_webid_gameid_package_orderId)
//        String remark = userId + "_" + platform + "_" + iapGiftId + "_" + ServerParam.MOTU_WEBID + "_" + ServerParam.MOTU_SDK_GAMEID + "_" + packageName + "_" + orderId;
//        JsonObject objRemark = new JsonObject();
//        objRemark.put("cpRemark", remark);
//        objRemark.put("efunProductId", productId);
//        objRemark.put("timestamp", System.currentTimeMillis());
//        String postData = "gameCode=" + loginKey + "&remark=" + objRemark.toString();
//        Buffer buffer = Buffer.buffer(postData, "UTF-8");
//        String url = "https://pay.efunjp.com/remark/encrypt.shtml";
//        MainVerticle.logger.info("getEfunParams userId:{} postData:{}", userId, postData);
//        MainVerticle.instance.webClient.postAbs(url).putHeader("content-type", "application/x-www-form-urlencoded").timeout(ServerParam.EFUN_HTTP_TIMEOUT).sendBuffer(buffer, res -> {
//            if (res.succeeded()) {
//                HttpResponse<Buffer> response = res.result();
//                MainVerticle.logger.info("getEfunParams userId:{} response:{}", userId, response.bodyAsString());
//                JsonObject resObj = response.bodyAsJsonObject();
//                String code = resObj.getString("code");
//                int ret;
//                if (code.equals("1000")){// 处理成功
//                    ret = ErrorWord.SUCCESS.value;
//                } else{
//                    ret = ErrorWord.TOKEN_WRONG.value;
//                }
//                JsonObject obj = new JsonObject();
//                obj.put("ret", ret);
//                if (ret == ErrorWord.SUCCESS.value) {
//                    JsonObject data = resObj.getJsonObject("data");
//                    obj.put("remark", data.getString("remark"));
//                }
//                onComplete.handle(Future.succeededFuture(obj));
//            } else {
//                if (retry >= ServerParam.EFUN_HTTP_RETRY){
//                    MainVerticle.logger.error("getEfunParams timeout retry max userId:{} cpRemark:{} cause:{}", userId, remark, Tool.getException(res.cause()));
//                    JsonObject obj = new JsonObject();
//                    obj.put("ret", ErrorWord.INVALID_OPERATION.value);
//                    onComplete.handle(Future.succeededFuture(obj));
//                } else{
//                    // 重试
//                    MainVerticle.logger.error("getEfunParams timeout retry:{} userId:{} cpRemark:{}", retry + 1, userId, remark);
//                    getEfunParams(userId, platform, iapGiftId, orderId, packageName, productId, retry + 1, onComplete);
//                }
//            }
//        });
//    }
//
//    /**
//     * 获取bilibili下单签名参数
//     */
//    private static String getBilibiliParams(double money, String orderId) {
//        Map<String, String> paramMap = new HashMap<>();
//        paramMap.put("game_money", String.valueOf((int)money * 10));
//        paramMap.put("money", String.valueOf((int)money * 100));
//        paramMap.put("notify_url", AllParam.BILIBILI_NOTIFY_URL);
//        paramMap.put("out_trade_no", orderId);
//        String sign = BilibiliApi.getSign(paramMap, ServerParam.BILIBILI_SECRET_KEY);
//        return sign;
//    }

    //   CMD_GAME_IAP_RECORD = 72214; // 充值记录
    public static Object CMD_GAME_IAP_RECORD(RequestParam clientParam) throws Exception {
        CSGameIapRecordResponse.Builder res_build = CSGameIapRecordResponse.newBuilder();
        long userId = clientParam.getUserId();
        List<IapRecord> iapRecordList = IapManager.getIapRecordList(userId);
        for (IapRecord iapRecord : iapRecordList) {
            IapGift iapGift = IapManager.getIapGift(iapRecord.getIapGiftId());
            if (iapGift != null && iapGift.getType() != IapGift.TYPE_WEB_RECHARGE) {
                res_build.addIapRecordList(iapRecord.takeBuilder());
            }

        }
        return res_build;
    }

    // CMD_GAME_IAP_GROWTH_FUND_INFO = 72210; // 成长基金界面
    public static Object CMD_GAME_IAP_GROWTH_FUND_INFO(RequestParam clientParam) throws Exception {
        CSGameIapGrowthFundInfoResponse.Builder response = CSGameIapGrowthFundInfoResponse.newBuilder();
        long userId = clientParam.getUserId();
        List<UserGrowthFund> userGrowthFundList = IapManager.getUserGrowthFundList(userId);
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        for(UserGrowthFund userGrowthFund : userGrowthFundList){
            ProtoDataUtils.updatePBUserData(pbUserData, userGrowthFund, true);
        }
        return response;
    }

    // CMD_GAME_IAP_GROWTH_FUND_REWARD = 72211; // 成长基金领奖
    public static Object CMD_GAME_IAP_GROWTH_FUND_REWARD(RequestParam clientParam) throws Exception {
        CSGameIapGrowthFundRewardRequest request = CSGameIapGrowthFundRewardRequest.parseFrom(clientParam.getData());
        CSGameIapGrowthFundRewardResponse.Builder response = CSGameIapGrowthFundRewardResponse.newBuilder();
        long userId = clientParam.getUserId();
        int type = request.getType();
        int groupId;
        UserGrowthFund userGrowthFund = IapManager.getUserGrowthFund(userId,type);
        boolean isCreate = false;
        if (userGrowthFund == null) {
            userGrowthFund = new UserGrowthFund(userId, type);
        }
        int[] GROWTH_FUND = userGrowthFund.getGrowthFund();
        ConcurrentHashMap<Long, GrowthFund> growthFundGroupMap = null;
        for (groupId = 1; groupId <= GROWTH_FUND.length; groupId++) {
             growthFundGroupMap = IapManager.getGrowthFundGroupMap(type,groupId);
            if (growthFundGroupMap == null) {
                return ErrorWord.BAD_PARAM;
            }
            if (groupId == GROWTH_FUND.length
                    || userGrowthFund.getFreeRewardAry(groupId).size() < growthFundGroupMap.size()
                    || !userGrowthFund.isBuy(groupId)
                    || userGrowthFund.getPayRewardAry(groupId).size() < growthFundGroupMap.size()) {
                break;
            }
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        long num = request.getNum();//0:一键领取
        if(num == 0)  {
            //一键领取
            JsonArray freeRewardAry = userGrowthFund.getFreeRewardAry(groupId);
            JsonArray payRewardAry = userGrowthFund.getPayRewardAry(groupId);
            boolean isBuy = userGrowthFund.isBuy(groupId);
            List<GrowthFund> freeList = new ArrayList<>();//可领免费奖励
            List<GrowthFund> payList = new ArrayList<>();//可领付费奖励
            long achieveNum = MainTaskManager.takeGrowthProgress(userInfo,type);

            for (GrowthFund growthFund : growthFundGroupMap.values()) {
                // 不满足领奖条件
                if (achieveNum < growthFund.getNum()) {
                    continue;
                }
                if (!Tool.isInList(freeRewardAry,growthFund.getNum())) {
                    freeList.add(growthFund);
                }
                if (isBuy && !Tool.isInList(payRewardAry,growthFund.getNum())) {
                    payList.add(growthFund);
                }
            }
            if (freeList.size() == 0 && payList.size() == 0) {
                return ErrorWord.NOT_DATA;
            }
            Common.PBUserData.Builder pbUserData = response.getUserBuilder();
            for (GrowthFund growthFund : freeList) {
                freeRewardAry.add(growthFund.getNum());
                userGrowthFund.setFreeReward(freeRewardAry.toString(), groupId);
                RewardManager.addReward(userInfo, growthFund.getFreeRewardList(), pbUserData, LogType.GROWTHFUND_FREE,type, groupId,growthFund.getNum());
            }
            for (GrowthFund growthFund : payList) {
                payRewardAry.add(growthFund.getNum());
                userGrowthFund.setPayReward(payRewardAry.toString(), groupId);
                RewardManager.addReward(userInfo, growthFund.getPayRewardList(), pbUserData, LogType.GROWTHFUND_FREE,type, groupId,growthFund.getNum());
            }

            if (isCreate) {
                userGrowthFund.doCreate();
            }else {
                userGrowthFund.update();
            }
            ProtoDataUtils.updatePBUserData(pbUserData, userGrowthFund, false);
        } else {
            GrowthFund growthFund = IapManager.getGrowthFund(type,groupId, num);
            // 参数错误
            if (growthFund == null) {
                return ErrorWord.BAD_PARAM;
            }
            long achieveNum = MainTaskManager.takeGrowthProgress(userInfo,type);

            // 不满足领奖条件
            if (achieveNum < growthFund.getNum()) {
                return ErrorWord.NOT_DATA;
            }
            JsonArray freeRewardAry = userGrowthFund.getFreeRewardAry(groupId);
            JsonArray payRewardAry = userGrowthFund.getPayRewardAry(groupId);
            // 没有可领取奖励
            if (Tool.isInList(freeRewardAry,growthFund.getNum())) {
                if (!userGrowthFund.isBuy(groupId) || Tool.isInList(payRewardAry,growthFund.getNum())) {
                    return ErrorWord.NOT_DATA_1;
                }
            }
            Common.PBUserData.Builder pbUserData = response.getUserBuilder();

            if (!Tool.isInList(freeRewardAry,growthFund.getNum())) {
                freeRewardAry.add(growthFund.getNum());
                userGrowthFund.setFreeReward(freeRewardAry.toString(), groupId);
                RewardManager.addReward(userInfo, growthFund.getFreeRewardList(), pbUserData, LogType.GROWTHFUND_FREE,type, groupId,growthFund.getNum());
            }
            if (userGrowthFund.isBuy(groupId) && !Tool.isInList(payRewardAry,growthFund.getNum())) {
                payRewardAry.add(growthFund.getNum());
                userGrowthFund.setPayReward(payRewardAry.toString(), groupId);
                RewardManager.addReward(userInfo, growthFund.getPayRewardList(), pbUserData, LogType.GROWTHFUND_PAY,type, groupId,growthFund.getNum());
            }
            if (isCreate) {
                userGrowthFund.doCreate();
            }else {
                userGrowthFund.update();
            }
            ProtoDataUtils.updatePBUserData(pbUserData, userGrowthFund, false);
        }


        return response;
    }


    //CMD_GAME_IAP_PRIVILEGE_CARD_INFO = 72212; // 特权卡界面
    public static Object CMD_GAME_IAP_PRIVILEGE_CARD_INFO(RequestParam clientParam) throws Exception {
        CSGameIapPrivilgeCardIInfoRequest request = CSGameIapPrivilgeCardIInfoRequest.parseFrom(clientParam.getData());
        CSGameIapPrivilgeCardIInfoResponse.Builder response = CSGameIapPrivilgeCardIInfoResponse.newBuilder();
        long userId = clientParam.getUserId();
        List<UserPrivilegeCard> userPrivilegeCardList = IapManager.getUserPrivilegeCardList(userId);
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        for(UserPrivilegeCard userPrivilegeCard : userPrivilegeCardList){
            ProtoDataUtils.updatePBUserData(pbUserData, userPrivilegeCard, true);
        }
        return response;
    }


    // CMD_GAME_IAP_PRIVILEGE_CARD_REWARD = 72213; // 特权卡每日奖励领取
    public static Object CMD_GAME_IAP_PRIVILEGE_CARD_REWARD(RequestParam clientParam) throws Exception {
        CSGameIapPrivilegeCardRewardRequest request = CSGameIapPrivilegeCardRewardRequest.parseFrom(clientParam.getData());
        CSGameIapPrivilegeCardRewardResponse.Builder response = CSGameIapPrivilegeCardRewardResponse.newBuilder();
        long userId = clientParam.getUserId();
        int type = request.getType();//0:领取全部
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserPower userPower = GameUser.getUserPower(userId);

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        if (type == 0) {
            List<UserPrivilegeCard> userPrivilegeCardList = IapManager.getUserPrivilegeCardList(userId);
            for (UserPrivilegeCard userPrivilegeCard : userPrivilegeCardList) {
                IapManager.getPrivilegeCardReward(pbUserData, userInfo, userPower, userPrivilegeCard);
            }
        } else{
            UserPrivilegeCard userPrivilegeCard = IapManager.getUserPrivilegeCard(userId,type);
            IapManager.getPrivilegeCardReward(pbUserData, userInfo, userPower, userPrivilegeCard);
        }

        return response;
    }

    //   CMD_GAME_IAP_VIP_GIFT_INFO = 72215; // VIP礼包初始化
    public static Object CMD_GAME_IAP_VIP_GIFT_INFO(RequestParam clientParam) throws Exception {
        CSGameIapVipGiftInfoResponse.Builder response = CSGameIapVipGiftInfoResponse.newBuilder();
        CSGameIapVipGiftInfoRequest request = CSGameIapVipGiftInfoRequest.parseFrom(clientParam.getData());
        long userId = clientParam.getUserId();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        List<IapGift> iapGiftTypeList = IapManager.getIapGiftTypeList(IapGift.TYPE_VIP);
        for ( IapGift iapGift : iapGiftTypeList) {
            UserIapGift userIapGift = IapManager.getUserIapGift(userId, iapGift.getId());
            if (userIapGift != null) {
                ProtoDataUtils.updatePBUserData(pbUserData, userIapGift,true);
            }
        }
        return response;
    }

    // CMD_GAME_IAP_VIP_REWARD = 72215; // VIP奖励领取
    public static Object CMD_GAME_IAP_VIP_REWARD(RequestParam clientParam) throws Exception {
        CSGameIapVipRewardRequest request = CSGameIapVipRewardRequest.parseFrom(clientParam.getData());
        CSGameIapVipRewardResponse.Builder response = CSGameIapVipRewardResponse.newBuilder();
        long userId = clientParam.getUserId();
        int level = request.getLevel();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (userInfo.getVip() < level) {
            return ErrorWord.INVALID_OPERATION;
        }
        JsonArray userInfoVipRewardArray = userInfo.getVipRewardArray();
        if (Tool.isInList(userInfoVipRewardArray,level)) {
            return ErrorWord.REPEATED_OPERATION;
        }
        userInfoVipRewardArray.add(level);
        userInfo.putVipReward(userInfoVipRewardArray.toString());
        userInfo.update();
        Vip vip = IapManager.getVipByLv(level);
        // 执行逻辑
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.addReward(userInfo, vip.getRewardItemList() , pbUserData, LogType.VIP_REWARD, level);
        ProtoDataUtils.updatePBUserData(pbUserData, userInfo);
        return response;
    }

    // CMD_GAME_IAP_RESET_GIFT_INFO = 72217; // 日月周重置礼包初始化
    public static Object CMD_GAME_IAP_RESET_GIFT_INFO(RequestParam clientParam) throws Exception {
        CSGameIapResetGiftInfoResponse.Builder response = CSGameIapResetGiftInfoResponse.newBuilder();
        CSGameIapResetGiftInfoRequest request = CSGameIapResetGiftInfoRequest.parseFrom(clientParam.getData());
        long userId = clientParam.getUserId();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        List<IapGift> iapGiftList = new ArrayList<>();
        List<IapGift> dayIapGiftTypeList = IapManager.getIapGiftTypeList(IapGift.TYPE_DAY);
        List<IapGift> weekIapGiftTypeList = IapManager.getIapGiftTypeList(IapGift.TYPE_WEEK);
        List<IapGift> monthIapGiftTypeList = IapManager.getIapGiftTypeList(IapGift.TYPE_MONTH);
        iapGiftList.addAll(dayIapGiftTypeList);
        iapGiftList.addAll(weekIapGiftTypeList);
        iapGiftList.addAll(monthIapGiftTypeList);
        for ( IapGift iapGift : iapGiftList) {
            UserIapGift userIapGift = IapManager.getUserIapGift(userId, iapGift.getId());
            if (userIapGift != null) {
                ProtoDataUtils.updatePBUserData(pbUserData, userIapGift,true);
            }
        }
        long curTime = TimeUtils.getCurTime();
        response.setNextDayTime(TimeUtils.getStartTimeOfDay(curTime) + TimeUtils.DAY);
        response.setNextWeekTime(TimeUtils.getNextDayOfWeek(curTime,1));
        response.setNextMonthTime(TimeUtils.getLastTimeOfMonth(curTime));
        return response;
    }

    // CMD_GAME_IAP_FIRST_CHARGE_REWARD = 72218; // 限时首日三天礼包领取
    public static Object CMD_GAME_IAP_FIRST_CHARGE_REWARD(RequestParam clientParam) throws Exception {
        CSGameIapFirstChargeRewardRequest request = CSGameIapFirstChargeRewardRequest.parseFrom(clientParam.getData());
        CSGameIapFirstChargeRewardResponse.Builder response = CSGameIapFirstChargeRewardResponse.newBuilder();
        long userId = clientParam.getUserId();
        int dayIndex = request.getDayIndex();
        if (dayIndex < 1 || dayIndex > 3) {
            return ErrorWord.BAD_PARAM;
        }
        UserInfo userInfo = GameUser.getUserInfo(userId);
        long curTime = TimeUtils.getCurTime();
        if (userInfo.getIsFirstCharge() == 0) {
            return ErrorWord.INVALID_OPERATION;
        }
        switch (dayIndex) {
            case 1:
                //购买当天可领取
                if (curTime < TimeUtils.getStartTimeOfDay(userInfo.getIsFirstCharge())) {
                    return ErrorWord.WRONG_STATUS;
                }
                break;
            case 2:
                //购买第二天可领取
                if (curTime < TimeUtils.getStartTimeOfDay(userInfo.getIsFirstCharge()) + TimeUtils.DAY) {
                    return ErrorWord.WRONG_STATUS;
                }
                break;
            case 3:
                //购买第三天可领取
                if (curTime < TimeUtils.getStartTimeOfDay(userInfo.getIsFirstCharge()) + TimeUtils.DAY * 2) {
                    return ErrorWord.WRONG_STATUS;
                }
                break;
        }
        JsonArray userInfoFirstChargeRewardArray = userInfo.getFirstChargeRewardArray();
        if (Tool.isInList(userInfoFirstChargeRewardArray,dayIndex)) {
            return ErrorWord.REPEATED_OPERATION;
        }
        userInfoFirstChargeRewardArray.add(dayIndex);
        userInfo.putFirstChargeReward(userInfoFirstChargeRewardArray.toString());
        userInfo.update();
        List<RewardItem> rewardItemList = new ArrayList<>();
        if (dayIndex == 1) {
            rewardItemList = RewardManager.itemsToList(AllParam.FIRST_CHARGE_REWAED_DAY_1);
        } else if (dayIndex == 2) {
            rewardItemList = RewardManager.itemsToList(AllParam.FIRST_CHARGE_REWAED_DAY_2);
        } else if (dayIndex == 3) {
            rewardItemList = RewardManager.itemsToList(AllParam.FIRST_CHARGE_REWAED_DAY_3);
        }
        // 执行逻辑
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.addReward(userInfo, rewardItemList , pbUserData, LogType.FIRST_CHARGE_REWARD, dayIndex);
        ProtoDataUtils.updatePBUserData(pbUserData, userInfo);
        return response;
    }

}
